<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/12
 * Time: 下午4:48
 */

namespace Superadmin\Controller;


use Org\Util\Tree;
use Think\Exception;

class AdminRoleController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->mod = D('admin_role');
    }

    //角色列表
    public function index()
    {
        $where = 1;
        $order = 'id asc';
        $list  = $this->getpage($this->mod,$where, $order);
        $this->assign('list', $list['list']);
        $this->assign('page', $list['page']);
        $big_menu = array(
            'title' => '新角色',
            'uri' => U('superadmin/admin_role/add'),
        );
        $this->assign('big_menu', $big_menu);
        $this->display();
    }


    //todo 添加角色
    public function add()
    {
        if(IS_AJAX)
        {
            $data = array(
                'name'    => I('post.name'),
                'status'  => I('post.status'),
                'addtime' => time(),
            );
            //检测是否重复
            if(D('admin_role')->is_exists(0, $data['name']))
            {
                $return = array(
                    'status' => 0,
                    'msg'    => '角色名重复'
                );
                $this->ajaxReturn($return);
            }
            try{
                if(!$data['name'])
                {
                    $return = array(
                        'status' => 0,
                        'msg'    => '新角色名称为必须',
                    );
                    $this->ajaxReturn($return);
                } else {
                    D('admin_role')->add($data);
                    $return = array(
                        'status' => 1,
                        'msg'    => L('operation_success')
                    );
                }

            } catch(Exception $e)
            {
                $msg = $e->getMessage();
                $return = array(
                    'status' => 0,
                    'msg'    => $msg
                );
            }
            $this->ajaxReturn($return);
        }
        $this->display();
    }

    //todo 编辑角色
    public function edit()
    {
        if(IS_AJAX)
        {
            $id   = I('id');
            $name = I('name');
            $status = I('status');
            if(!$name)
            {
                $return = array(
                    'status' => 0,
                    'msg'    => '角色名必须'
                );
                $this->ajaxReturn($return);
            }
            //检测是否重复
            if(D('admin_role')->is_exists($id, $name))
            {
                $return = array(
                    'status' => 0,
                    'msg'    => '角色名重复'
                );
                $this->ajaxReturn($return);
            }
            $data = array();
            if($id) $data = D('admin_role')->find($id);
            if(!$data)
            {
                $return = array(
                    'status' => 0,
                    'msg'    => '访问出错！'
                );
                $this->ajaxReturn($return);
            }
            $post = array(
                'name'   => $name,
                'status' => $status,
            );
            try{
                D('admin_role')->where(array('id' => $id))->save($post);
                $return = array(
                    'status' => 1,
                    'msg'    => L('operation_success')
                );
            } catch(Exception $e)
            {
                $msg = $e->getMessage();
                $return = array(
                    'status' => 0,
                    'msg'    => $msg
                );
            }
            $this->ajaxReturn($return);
        }
        $id = I('id');
        $data = D('admin_role')->find($id);
        $this->assign('data', $data);
        $this->display();
    }

    public function _before_save($id, $name)
    {
        //检测是否重复
        if(D('admin_role')->is_exists($id, $name))
        {
            $return = array(
                'status' => 0,
                'msg'    => '角色名重复'
            );
            $this->ajaxReturn($return);
        }
    }


    //todo 授权
    public function authorize()
    {
        $id = I('id');
        $tree = new Tree();
        $tree->icon = array('│ ','├─ ','└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $result = D('menu')->where(array('display'=>1))->order('ordid')->select();
        //获取被操作角色权限
        $role_data = D('admin_role')->relation('role_priv')->find($id);
        $priv_ids = array();
        foreach ($role_data['role_priv'] as $val) {
            $priv_ids[] = $val['id'];
        }
        foreach($result as $k=>$v) {
            $result[$k]['level'] = D('menu')->get_level($v['id'],$result);
            $result[$k]['checked'] = (in_array($v['id'], $priv_ids))? ' checked' : '';
            $result[$k]['parentid_node'] = ($v['pid'])? ' class="child-of-node-'.$v['pid'].'"' : '';
        }
        $str  = "<tr id='node-\$id' \$parentid_node>" .
            "<td style='padding-left:10px;'>\$spacer<input type='checkbox' name='menu_id[]' value='\$id' class='J_checkitem' level='\$level' \$checked> \$name</td>
                    </tr>";
        $tree->init($result);
        $menu_list = $tree->get_tree(0, $str);
        $this->assign('list', $menu_list);
        $this->assign('role', $role_data);
        $this->display();
    }

    //角色授权
    public function auth()
    {
       $role_id = I('id');
       $menu_ids = I('menu_id');
       $data = array();
       if($menu_ids)
       {
           //开始构造数据
           foreach($menu_ids as $key => $val)
           {
              if(intval($val))
              {
                  $auth[] = intval($val);
                  $data[] = array(
                      'role_id' => $role_id,
                      'menu_id' => intval($val),
                  );
              }
           }
       }
       if(!$role_id)
       {
           $this->error(L('no_source'), U('superadmin/admin_role/index'));
       }
       //删除角色所有的权限
       D('admin_auth')->where(array('role_id' => $role_id))->delete();
       //赋予新权限
       if($data)
       {
           D('admin_auth')->addAll($data);
           //缓存所有权限
           S('role_auth_'. $role_id,null);
           S('role_auth_'. $role_id, $auth, 86400);
       }
        $this->success(L('operation_success'), U('superadmin/admin_role/authorize',array('id'=>$role_id)));

    }

}